import Vue from 'vue'
import axios from 'axios'
import notification from 'ant-design-vue/es/notification'
import store from '@/store'
import { ACCESS_TOKEN } from '@/store/mutation-types'

// create an axios instance
// console.log('[process.env.BASE_API]',process.env.VUE_APP_BASE_API)
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // api的base_url
  withCredentials: true, // 跨域请求时发送 cookies
  timeout: 30000, // request timeout
  method:'post'
})

// request interceptor
service.interceptors.request.use(config => {
  // Do something before request is sent
  const token = Vue.ls.get(ACCESS_TOKEN)
  if (token) {
    // 让每个请求携带token
    config.headers['Authorization'] = token
  }
  return config
}, error => {
  // Do something with request error
  console.log(error) // for debug
  return Promise.reject(error)
})

// respone interceptor
service.interceptors.response.use(
  // response => response,
  /**
   * 下面的注释为通过在response里，自定义code来标示请求状态
   * 当code返回如下情况则说明权限有问题，登出并返回到登录页
   * 如想通过xmlhttprequest来状态码标识 逻辑可写在下面error中
   * 以下代码均为样例，请结合自生需求加以修改，若不需要，则可删除
   */
  response => {
    const res = response.data
    if (response.status !== 200) {
      notification.error({
        message: '禁止',
        description: res.msg
      })
      return Promise.reject('error')
    }else {
      // 50008:非法的token; 50012:其他客户端登录了;  50014:Token 过期了;
      if (res.code === -1) {
        notification.error({
          message: '授权到期',
          description: '请重新登录'
        })
        // store.dispatch('Logout').then(() => {
        //   location.reload() // 为了重新实例化vue-router对象 避免bug
        // })
      }else if (res.code == 1) {
        //统一处理异常提示
        notification.error({
          message: '出现问题',
          description: res.msg
        })
      }
      return res
    }
  },
  error => {
    console.log('err' ,error) // for debug
    if (error.response) {
      const data = error.response.data
      if (error.response.status === 502) {
        notification.error({
          message: '禁止',
          description: data.msg
        })
      }
      if (error.response.status === 403) {
        notification.error({
          message: '没有权限',
          description: data.msg
        })
      }
    }else {
      notification.error({
        message: '出现异常',
        description: error.message
      })
    }
    return Promise.reject(error)
  })

  function getUrlParam(name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)"); //构造一个含有目标参数的正则表达式对象
    var r = window.location.search.substr(1).match(reg);  //匹配目标参数
    if (r != null) return unescape(r[2]); return ''; //返回参数值
  }
export default service
